//
//  TestResultDetailViewController.m
//  Learn
//
//  Created by zyl_macbookpro on 2024/6/2.
//  Copyright © 2024 迟建国. All rights reserved.
//

#import "TestResultDetailViewController.h"
#import "TestResultDetailTableViewCell.h"
#import "AudioPlayProgressView.h"
#import "TextbookQuestionsModel.h"
#import "TestSubCellViewModel.h"
@interface TestResultDetailViewController ()

<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic ,strong)UITableView *tableView;

@property(nonatomic ,strong)UIView *tableHeaderView;

@property(nonatomic ,strong)UIView *tableFootorView;

@property(nonatomic ,strong)NSMutableArray *dataArray;

@property(nonatomic ,strong)NSMutableArray *openArray;

@property(nonatomic ,strong)NSDictionary *data;

@property (nonatomic, strong) TextbookQuestionsModel *model;
@end

@implementation TestResultDetailViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self renderNavBarWithBackgroundImage:[UIImage imageWithColor:lClearColor] backgroundColor:lClearColor shadowColor:nil textAttributeDic:@{NSForegroundColorAttributeName:lWhiteColor,NSFontAttributeName:MFontWithSize(18)} enableScrollEdgeAppearance:NO];
    
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[PlayManager sharPlayManager] pause];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
   
}
- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.dataArray = @[].mutableCopy;
    self.openArray = @[].mutableCopy;
    self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    [self.view addSubview:self.tableView];
    [self setWhiteBackButton];
    [self dealData];
    
}

#pragma mark -UITableViewDelegate,UITableViewDelegate
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TestResultDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TestResultDetailTableViewCell"];
    
    if (!cell)
    {
        cell = [[TestResultDetailTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TestResultDetailTableViewCell"];
        cell.selectionStyle =UITableViewCellSelectionStyleNone;
    }
    
    HSItem *model = self.dataArray[indexPath.section];
    TestSubCellViewModel *testModel = model.viewModel[indexPath.row];
    cell.resmain = self.model.resmain;
    cell.viewModel = testModel;
    return cell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    HSItem *model = self.dataArray[section];
    return [self.openArray containsObject:[NSNumber numberWithInteger:section]]? model.viewModel.count:0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    HSItem *model = self.dataArray[section];
    CGFloat height = [self getTextHeightWithWidth:lScreenWidth - 67 Font:MFontWithSize(16) Text:model.templateSettings.content]  + 10 + 16 + 10 + 1 + 15  + 5;
    return height;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.001;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return [UIView new];
}
- (double)getTextHeightWithWidth:(double)width Font:(UIFont *)font Text:(NSString *)text
{
    UILabel *titleLab = [[UILabel alloc] init];
    titleLab.frame = CGRectMake(10,10,width,CGFLOAT_MIN);
    titleLab.font = font;
    titleLab.numberOfLines = 0;
    titleLab.textColor = rgba(51, 51, 51, 1);
    titleLab.text = text;
    titleLab.textAlignment = NSTextAlignmentLeft;
    [titleLab sizeToFit];
    return titleLab.height;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    HSItem *model = self.dataArray[indexPath.section];
    TestSubCellViewModel *modelView = model.viewModel[indexPath.row];
   
    return modelView.rowHeight;
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    HSItem *model = self.dataArray[section];
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0,0,lScreenWidth,115)];
    UIView *view = [[UIView alloc] init];
    view.frame = CGRectMake(10,0,lScreenWidth - 20,115);
    view.backgroundColor = lWhiteColor;
    [headerView addSubview:view];
    UIButton *btn = ({
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(lScreenWidth - 20 - 37, 0, 30, 30);
        [button setImage:[UIImage imageNamed:@"ic_arrow_down"] forState:UIControlStateNormal];
        [button setImage:[UIImage imageNamed:@"ic_arrow_up"] forState:UIControlStateSelected];
        button;
    });
    
    btn.tag = section;
    [btn addTarget:self action:@selector(showButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:btn];
    btn.selected = [self.openArray containsObject:[NSNumber numberWithInteger:section]];
    UILabel *scoreAllTitleLab = [[UILabel alloc] init];
    scoreAllTitleLab.frame = CGRectMake(10,5,lScreenWidth - 67,CGFLOAT_MIN);
    [view addSubview:scoreAllTitleLab];
    scoreAllTitleLab.font = SFontWithSize(16);
    scoreAllTitleLab.numberOfLines = 0;
    scoreAllTitleLab.textColor = rgba(51, 51, 51, 1);
    scoreAllTitleLab.text = model.templateSettings.content;;
    scoreAllTitleLab.textAlignment = NSTextAlignmentLeft;
    [scoreAllTitleLab sizeToFit];
    UILabel *scoreAllLab = [[UILabel alloc] init];
    scoreAllLab.frame = CGRectMake(10,scoreAllTitleLab.bottom + 10,lScreenWidth - 67,16);
    [view addSubview:scoreAllLab];
    btn.centerY = scoreAllTitleLab.centerY;
    scoreAllLab.font = SFontWithSize(16);
    scoreAllLab.textColor = rgba(51, 51, 51, 1);
    
    NSString *score = [NSString stringWithFormat:@"%.1f",model.getScore]; ;
    double fscore = model.fullscore;
    NSMutableAttributedString *att = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"(%@分/%.1f分)",score,fscore]];
    [att addAttribute:NSForegroundColorAttributeName value:rgba(250, 25, 44, 1) range:NSMakeRange(1, score.length + 1)];
    scoreAllLab.attributedText = att;
    
    UIView *viewLine = [[UIView alloc] init];
    viewLine.frame = CGRectMake(10,scoreAllLab.bottom + 10,lScreenWidth - 20,1);
    viewLine.backgroundColor = rgba(229, 229, 229, 1);
    [headerView addSubview:viewLine];
    
    view.height = 5 + scoreAllTitleLab.height + 10 + scoreAllLab.height + 10 + 1 + 15;
   
    headerView.clipsToBounds = YES;
    return headerView;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}
#pragma mark -event response
- (void)showButtonClick:(UIButton *)button
{
    button.selected = !button.selected;
    if ([self.openArray containsObject:[NSNumber numberWithInteger:button.tag]]) {
        [self.openArray removeObject:[NSNumber numberWithInteger:button.tag]];
    }else{
        [self.openArray addObject:[NSNumber numberWithInteger:button.tag]];
    }
    [self.tableView reloadSection:button.tag withRowAnimation:UITableViewRowAnimationFade];
}



#pragma mark -getters and setters
-(UITableView *)tableView{
    if (!_tableView){
        _tableView =[[UITableView alloc] initWithFrame:CGRectMake(0, 0, lScreenWidth, lScreenHeight) style:UITableViewStyleGrouped];
        [_tableView setDelegate:self];
        [_tableView setDataSource:self];
        _tableView.bounces = NO;
        [_tableView setBackgroundColor:rgba(245, 245, 245, 1)];
        [_tableView setSeparatorColor:lClearColor];
        [_tableView setSeparatorInset:UIEdgeInsetsMake(0, 10, 0, 0)];
        [_tableView setTableHeaderView:self.tableHeaderView];
        [_tableView setTableFooterView:self.tableFootorView];
    }
    
    return _tableView;
}
- (UIImage *)imageWithBase64String:(NSString *)base64String {
    NSURL *URL = [NSURL URLWithString:base64String];
    NSData *imageData = [NSData dataWithContentsOfURL:URL];
    UIImage *image = [UIImage imageWithData:imageData];
    return image;
}
-(UIView *)tableHeaderView
{
    if (!_tableHeaderView)
    {
        _tableHeaderView =[[UIView alloc] initWithFrame:CGRectMake(0, 0, lScreenWidth,260/375.0*lScreenWidth + 72)];
        _tableHeaderView.backgroundColor = rgba(245, 245, 245, 1);
        UIImageView *headerBgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, lScreenWidth, 270.0/375*lScreenWidth)];
        headerBgImageView.image = IMAGENAMED(@"ic_test_result_detail_bg");
        
        
        [_tableHeaderView addSubview:headerBgImageView];
        
        UILabel *scoreL = [[UILabel alloc] initWithFrame:CGRectMake(10, lTopBarHeight + 30, lScreenWidth - 20, 92)];
        scoreL.text = [NSString stringWithFormat:@"%.2f",[self.data[@"score"] doubleValue]];
        scoreL.textColor = UIColor.whiteColor;
        scoreL.font = MFontWithSize(66);
        scoreL.textAlignment = NSTextAlignmentCenter;
        [_tableHeaderView addSubview:scoreL];
        
        
        UILabel *levelLab = [[UILabel alloc] initWithFrame:CGRectMake(10, scoreL.bottom + 5, lScreenWidth - 20, 25)];
        double scoreLevel = [self.data[@"score"] doubleValue]/[self.data[@"full_score"] doubleValue];
        scoreLevel = scoreLevel > 1? 100:scoreLevel*100;
        levelLab.text = [NSString stringWithFormat:@"得分率 %.2f%@", scoreLevel,@"%"];
        levelLab.textColor = UIColor.whiteColor;
        levelLab.font = SFontWithSize(18);
        levelLab.textAlignment = NSTextAlignmentCenter;
        [_tableHeaderView addSubview:levelLab];
        
        UIView *view = [[UIView alloc] init];
        view.frame = CGRectMake(10,headerBgImageView.bottom + 10,lScreenWidth - 20,115);
        view.backgroundColor = lWhiteColor;
        view.layer.cornerRadius = 15;
        view.layer.masksToBounds = YES;
        
        [_tableHeaderView addSubview:view];
        
        UILabel *scoreAllTitleLab = [[UILabel alloc] init];
        scoreAllTitleLab.frame = CGRectMake(10,0,lScreenWidth/2.0 - 20,57);
        [view addSubview:scoreAllTitleLab];
        NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"总分"attributes: @{NSFontAttributeName: SFontWithSize(16),NSForegroundColorAttributeName: [UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:1.0]}];
        scoreAllTitleLab.attributedText = string;
        scoreAllTitleLab.textAlignment = NSTextAlignmentLeft;
        
        UILabel *scoreAllLab = [[UILabel alloc] init];
        scoreAllLab.frame = CGRectMake(scoreAllTitleLab.right,0,lScreenWidth/2.0 - 20,57);
        [view addSubview:scoreAllLab];
        NSString *totalScore = [NSString stringWithFormat:@"%.2f分" ,[self.data[@"full_score"] doubleValue]];
        NSMutableAttributedString *stringS = [[NSMutableAttributedString alloc] initWithString:totalScore attributes: @{NSFontAttributeName: SFontWithSize(16),NSForegroundColorAttributeName: rgba(12, 183, 108, 1)}];
        scoreAllLab.attributedText = stringS;
        scoreAllLab.textAlignment = NSTextAlignmentRight;
        [view addSubview:separateLineWithColor(CGRectMake(10, 57, scoreAllLab.width*2, 1), rgba(229, 229, 229, 1))];
        
        UILabel *timeTitleLab = [[UILabel alloc] init];
        timeTitleLab.frame = CGRectMake(10,scoreAllLab.bottom + 1,lScreenWidth/2.0 - 20,57);
        [view addSubview:timeTitleLab];
        NSMutableAttributedString *stringT = [[NSMutableAttributedString alloc] initWithString:@"作答用时"attributes: @{NSFontAttributeName: SFontWithSize(16),NSForegroundColorAttributeName: [UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:1.0]}];
        timeTitleLab.attributedText = stringT;
        timeTitleLab.textAlignment = NSTextAlignmentLeft;
        
        UILabel *timeLab = [[UILabel alloc] init];
        timeLab.frame = CGRectMake(scoreAllTitleLab.right,scoreAllLab.bottom + 1,lScreenWidth/2.0 - 20,57);
        [view addSubview:timeLab];
        if (self.data[@"use_time"]) {
//            NSString *time = [NSString stringWithFormat:@"%dmin%ds",[self.data[@"use_time"] intValue]/60,[self.data[@"use_time"] intValue]%60];
//            if ([self.data[@"use_time"] intValue]< 60) {
//                time = [NSString stringWithFormat:@"%ds",[self.data[@"use_time"] intValue]];
//            }
            
            NSMutableAttributedString *stringTS = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@",self.data[@"use_time"]] attributes: @{NSFontAttributeName: SFontWithSize(16),NSForegroundColorAttributeName: rgba(51, 51, 51, 1)}];
            timeLab.attributedText = stringTS;
        }
        
        timeLab.textAlignment = NSTextAlignmentRight;
        
        UIView *topCornerView = [[UIView alloc] init];
        topCornerView.frame = CGRectMake(10,view.bottom + 10,lScreenWidth - 20,15);
        topCornerView.backgroundColor = lWhiteColor;
        [_tableHeaderView addSubview:topCornerView];
        [topCornerView setCorners:UIRectCornerTopLeft|UIRectCornerTopRight cornerRadius:15];
        _tableHeaderView.height = topCornerView.bottom;
    }
    
    return _tableHeaderView;
}

-(UIView *)tableFootorView
{
    if (!_tableFootorView)
    {
        _tableFootorView =[[UIView alloc] initWithFrame:CGRectMake(0, 0, lScreenWidth - 20, 30 + lBottomDangerousAreaHeight)];
        _tableFootorView.backgroundColor = lClearColor;
        UIView *bottomCornerView = [[UIView alloc] init];
        bottomCornerView.frame = CGRectMake(10,0,lScreenWidth - 20,15);
        bottomCornerView.backgroundColor = lWhiteColor;
        [_tableFootorView addSubview:bottomCornerView];
        [bottomCornerView setCorners:UIRectCornerBottomLeft|UIRectCornerBottomRight cornerRadius:15];
    }
    
    return _tableFootorView;
}

- (void)dealData
{
    self.dataArray = @[].mutableCopy;
    NSMutableArray *aArray = @[].mutableCopy;
    for (int i = 0;  i < self.model.resource.items.count;i++) {
        HSItem *item = self.model.resource.items[i];
        NSDictionary *dic = [item mj_keyValues].mutableCopy;
        HSItem *new = [HSItem mj_objectWithKeyValues:dic];
        new.fullscore = 0;
        new.getScore = 0;
        NSMutableArray *array = @[].mutableCopy;
        
        for (HSQuestion *quest in item.questions) {
            [array addObject:quest];
            new.fullscore = new.fullscore + quest.score;
            new.getScore = new.getScore + quest.questionRefSorce;
            if (quest.children.count == 0) {
                [aArray addObject:quest];
            }else{
                [array addObjectsFromArray:[self getQuestionWithQuestion:quest item:item]];
                [aArray addObjectsFromArray:[self getQuestionWithQuestion:quest item:new]];
            }
        }
        
        NSMutableArray *array1 = @[].mutableCopy;
        
        for (int a = 0; a < array.count; a++) {
            
            HSQuestion *quest = array[a];
            TestSubCellViewModel *model = [TestSubCellViewModel new];
            model.question = quest;
            HSValueAttachment *k= quest.trunk.attachments[0];
            HSValueAttachment *attImg= [HSValueAttachment new];
            model.rowHeight = 0;
            __block double height = 62;
            for (HSValueAttachment *att in quest.trunk.attachments) {
                if (att.fileType == 2) {
                    k = att;
                   
                }
                if (att.fileType == 1){
                    attImg = att;
                }
            }
            
                if (k.url.length != 0) {
                    height =  height + 22;
                    height =  height + 8;
                }
            
            if (attImg.url.length > 0){
                [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",self.model.resmain,attImg.url]] completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
                    model.img = image;
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if (model.img) {
                            model.rowHeight = model.rowHeight + model.img.size.height/model.img.size.width*(SCREEN_W - 40) + 10;
                        }
                        [self.tableView reloadData];
                    });
                }];
            }
            
            height = height + [self getTextHeightWithWidth:SCREEN_W - 40 Font:MFontWithSize(16) Text:quest.trunk.body] + 10;
           
            if (quest.recordUrl.length != 0) {
                height =  height + 32;
                height =  height + 13;
                height =  height + 22;
                height =  height + 8;
            }
            
            height =  height + 32;
            height =  height + 10;
            height =  height + [self getTextHeightWithWidth:SCREEN_W - 40 Font:MFontWithSize(16) Text:quest.answer];
            NSLog(@"^^^^^^^^%f+%@",[self getTextHeightWithWidth:SCREEN_W - 40 Font:MFontWithSize(16) Text:quest.answer],quest.answer);
            height =  height + 5;
            model.rowHeight = model.rowHeight+height;
            [array1 addObject:model];
        }
        
        new.viewModel = array1;
        [self.dataArray addObject:new];
    }
    
    [self.tableView reloadData];
}
-(NSMutableArray *)getQuestionWithQuestion:(HSQuestion *)question item:(HSItem *)item
{
    NSMutableArray *aArray = @[].mutableCopy;
    for (HSQuestion *quest in question.children) {
        item.fullscore = item.fullscore + quest.score;
        item.getScore = item.getScore + quest.questionRefSorce;
        [aArray addObject:quest];
    }
    return aArray;
}
- (void)setParaObject:(NSObject *)paraObject
{
    self.data = (NSDictionary *)paraObject;
    self.model = [TextbookQuestionsModel mj_objectWithKeyValues:self.data[@"json"]];
}
@end
